package com.kingyea.gradle.jsch;

import java.text.DecimalFormat;

import org.apache.commons.io.FilenameUtils;

import com.jcraft.jsch.SftpProgressMonitor;

public class UploadSftpProgressMonitor implements SftpProgressMonitor {
	//private int op;
	private String src;
	//private String dest;
	private long max;
	//已上传数据大小(byte)
	private long uploaded;
	//上传的数据块数量
	private int blocks;
	//每上传多少个数据块输出一次当前进度
	private int blockInterval = 10;

	@Override
	public void init(int op, String src, String dest, long max) {
		//this.op = op;
		this.src = src;
		//this.dest = dest;
		this.max = max;
	}

	@Override
	public boolean count(long count) {
		addUploaded(count);
		if(blocks % blockInterval==0) {
			final int process = max==0 ? 100 : (int) (getUploaded() * 100 / max);
			System.out.println(String.format("Uploading [%d%%][%s] %s", process, calFriendlyFileSize(), getFilename(src)));
		}
		return true;
	}

	@Override
	public void end() {
		System.out.println(String.format("upload [%s] complete.", getFilename(src)));
		reset();
	}

	private void reset() {
		this.src = null;
		//this.dest = null;
		this.max = 0;
		this.uploaded = 0;
		this.blocks = 0;
	}

	private String calFriendlyFileSize() {
		DecimalFormat format = new DecimalFormat("#.##");
		String answer = null;
		if(max<1024) {
			answer = max + "b";
		} else if(max<1024 * 1024) {
			answer = format.format(max/1024.0) + "Kb";
		} else if(max<1024 * 1024 * 1024) {
			answer = format.format(max/1024.0/1024.0) + "Mb";
		} else {
			answer = format.format(max/1024.0/1024.0/1024.0) + "Gb";
		}
		return answer;
	}
	
	private void addUploaded(long uploaded) {
		this.uploaded += uploaded;
		this.blocks++;
	}
	
	public long getUploaded() {
		return uploaded;
	}

	public int getBlockInterval() {
		return blockInterval;
	}

	public void setBlockInterval(int blockInterval) {
		this.blockInterval = blockInterval;
	}

	private String getFilename(String path) {
		return FilenameUtils.getName(path);
	}
}
